package com.example.myanimator.circleanimator

import android.animation.Animator
import android.view.View.MeasureSpec
import android.animation.ValueAnimator
import android.animation.ValueAnimator.AnimatorUpdateListener
import android.animation.AnimatorListenerAdapter
import android.content.Context
import android.content.res.TypedArray
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.view.View
import com.example.myanimator.R
import com.example.myanimator.circleanimator.CircleAnimatorView

/**
 * @author tgw
 * @date 2021/3/26
 * @describe
 */
class CircleAnimatorView1(context: Context, attrs: AttributeSet?) : View(context, attrs) {
    private lateinit var mCirclePath: Path
    private lateinit var mDstPath: Path
    private lateinit var circleValueAnimator: ValueAnimator
    private var mPaint: Paint
    private var mPaintBg: Paint
    private lateinit var mPathMeasure: PathMeasure
    private var mCurAnimValue = 0f
    private var endLength = 0f
    private var mBgColor = Color.parseColor("#FF1FB5AB")
    private var mProgressBgColor = Color.parseColor("#FFF5F5F5")
    private var mProgressWidth = 30f
    private var mCircleRadius = 30f
    private var mIsNeedAnimator = false
    private var mViewHeight = 0
    private var mViewWidth = 0
    //动画圆倒计时,计算已运行的长度
    private var runningDurationLength:Float = 0f


    init {
        setLayerType(LAYER_TYPE_SOFTWARE, null)
        if (attrs != null) {
            val typedArray =
                getContext().obtainStyledAttributes(attrs, R.styleable.CircleAnimatorView)
            mBgColor = typedArray.getColor(R.styleable.CircleAnimatorView_bgColor, mBgColor)
            mProgressBgColor = typedArray.getColor(
                R.styleable.CircleAnimatorView_animationProgressColor,
                mProgressBgColor
            )
            mProgressWidth = dip2px(
                context,
                typedArray.getDimension(
                    R.styleable.CircleAnimatorView_progressWidth,
                    mProgressWidth
                )
            )
            mCircleRadius = dip2px(
                context,
                typedArray.getDimension(R.styleable.CircleAnimatorView_circleRadius, mCircleRadius)
            )
            mIsNeedAnimator =
                typedArray.getBoolean(R.styleable.CircleAnimatorView_isNeedAnimation, mIsNeedAnimator)

        }
        //画笔初始化
        mPaint = Paint()
        mPaint.isAntiAlias = true // 去除锯齿
        mPaint.strokeWidth = mProgressWidth
        mPaint.style = Paint.Style.STROKE
        mPaint.color = mProgressBgColor
        mPaintBg = Paint()
        mPaintBg.isAntiAlias = true // 去除锯齿
        mPaintBg.strokeWidth = mProgressWidth
        mPaintBg.style = Paint.Style.STROKE
        mPaintBg.color = mBgColor
    }


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
//        mViewWidth = MeasureSpec.makeMeasureSpec(widthMeasureSpec, MeasureSpec.AT_MOST)
//        mViewHeight = MeasureSpec.makeMeasureSpec(heightMeasureSpec, MeasureSpec.AT_MOST)
        mViewWidth = measureWidthOrHeight(widthMeasureSpec)
        mViewHeight = measureWidthOrHeight(heightMeasureSpec)
        setMeasuredDimension(mViewWidth, mViewHeight)
        //        mViewHeight = getMeasuredHeight();
//        mViewWidth = getMeasuredWidth();
        Log.d("tgw", "宽度init-onMeasuremViewWidth: " + mViewWidth + "mViewHeight:" + mViewHeight)
        init()
    }

    private fun measureWidthOrHeight(measureSpec: Int): Int {
        var result = 0
        //获取当前View的测量模式
        val mode = MeasureSpec.getMode(measureSpec)
        //精准模式获取当前Viwe测量后的值,如果是最大值模式,会获取父View的大小.
        val size = MeasureSpec.getSize(measureSpec)
        if (mode == MeasureSpec.EXACTLY) {
            //当测量模式为精准模式,返回设定的值
            result = size
        } else {
            //设置为WrapContent的默认大小,圆的直径加上画笔宽度
            result = (mCircleRadius * 2 + mProgressWidth).toInt()
            if (mode == MeasureSpec.AT_MOST) {
                //当模式为最大值的时候,默认大小和父类View的大小进行对比,返回最小的值
                result = Math.min(result, size)
            }
        }
        return result
    }

    private fun init() {
        Log.d("tgw", "宽度init: $mProgressWidth")
        val path = mCircleRadius * 2
        val left = (mViewWidth - mCircleRadius * 2) / 2
        val top = (mViewHeight - mCircleRadius * 2) / 2
        //画圆
        val rectFTo = RectF(left, top, path + left, path + top)
        mCirclePath = Path()
        mDstPath = Path()
        mCirclePath.addArc(rectFTo, -90f, -360f)
        mPathMeasure = PathMeasure(mCirclePath, true)
//        setCircleValueAnimatorStart(4000f,0.25f)
    }

    /**
     *@param duration  总周期
     *@param runningDuration 已运行周期
     */
    fun setCircleValueAnimatorStart(duration:Float,runningDuration:Float){
        var runningProgress = 0f
        if (runningDuration<=0){
            runningDurationLength = mPathMeasure.length
        }else{
            //动画圆倒计时,计算已运行的长度
            runningDurationLength = runningDuration/duration*mPathMeasure.length
            runningProgress = runningDuration/duration
        }
        circleValueAnimator = ValueAnimator.ofFloat(0f, 1f)
//        circleValueAnimator.repeatCount = ValueAnimator.INFINITE
        circleValueAnimator.duration = duration.toLong()
        circleValueAnimator.addUpdateListener { animation ->
            mCurAnimValue = (animation.animatedValue as Float)+runningProgress
            if (mCurAnimValue<=1f){
                postInvalidate()
            }
        }
        circleValueAnimator.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: Animator) {
                super.onAnimationEnd(animation)
                Log.d("tgw2","动画结束");

            }
        })
//        if (!circleValueAnimator.isStarted && mIsNeedAnimator) {
        ValueAnimatorUtil.resetDurationScaleIfDisable()
        circleValueAnimator.start()
//        }
    }




    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.drawPath(mCirclePath, mPaintBg)
        if (mIsNeedAnimator){
            drawAnimationCircle(canvas)
        }
    }

    private fun drawAnimationCircle(canvas: Canvas) {
        endLength = (mPathMeasure.length * mCurAnimValue)
        mDstPath.reset()
        Log.d("tgw2-PathMeasure", "mPathMeasure-endLength: " + endLength + "圆绘制 动画进度" + mCurAnimValue+"mPathMeasurelength:"+  mPathMeasure.getLength());
        mPathMeasure.getSegment(0f, endLength, mDstPath, true)
        canvas.drawPath(mDstPath, mPaint)
    }

    companion object {
        fun dip2px(context: Context, dpValue: Float): Float {
            val scale = context.resources.displayMetrics.density
            return dpValue * scale + 0.5f
        }
    }

}